// pages/cart/cart.js
import { cartApi } from '../../utils/api.js'
import { checkLoginAndRedirect } from '../../utils/auth.js'
import { formatPrice } from '../../utils/format.js'

const app = getApp()

Page({
  data: {
    loading: true,
    cartItems: [],
    totalAmount: 0,
    selectedItems: [],
    allSelected: false
  },

  onLoad() {
    this.loadCartData()
  },

  onShow() {
    // 每次显示时重新加载购物车数据
    this.loadCartData()
  },

  onPullDownRefresh() {
    this.loadCartData()
  },

  // 加载购物车数据
  async loadCartData() {
    if (!checkLoginAndRedirect()) {
      this.setData({ loading: false })
      return
    }

    try {
      this.setData({ loading: true })
      
      const res = await cartApi.getList()
      
      if (res.code === 1) {
        const cartItems = res.data || []
        this.setData({
          cartItems,
          selectedItems: cartItems.map(item => item.id), // 默认全选
          allSelected: cartItems.length > 0
        })
        this.calculateTotal()
      }
    } catch (error) {
      console.error('加载购物车失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
      wx.stopPullDownRefresh()
    }
  },

  // 计算总价
  calculateTotal() {
    const { cartItems, selectedItems } = this.data
    let totalAmount = 0
    
    cartItems.forEach(item => {
      if (selectedItems.includes(item.id)) {
        totalAmount += item.amount * item.number
      }
    })
    
    this.setData({
      totalAmount: formatPrice(totalAmount)
    })
  },

  // 选择/取消选择商品
  toggleItemSelection(e) {
    const itemId = e.currentTarget.dataset.id
    const selectedItems = [...this.data.selectedItems]
    const index = selectedItems.indexOf(itemId)
    
    if (index > -1) {
      selectedItems.splice(index, 1)
    } else {
      selectedItems.push(itemId)
    }
    
    this.setData({
      selectedItems,
      allSelected: selectedItems.length === this.data.cartItems.length
    })
    this.calculateTotal()
  },

  // 全选/取消全选
  toggleAllSelection() {
    const { cartItems, allSelected } = this.data
    const selectedItems = allSelected ? [] : cartItems.map(item => item.id)
    
    this.setData({
      selectedItems,
      allSelected: !allSelected
    })
    this.calculateTotal()
  },

  // 增加商品数量
  async increaseQuantity(e) {
    const itemId = e.currentTarget.dataset.id
    const item = this.data.cartItems.find(item => item.id === itemId)
    
    if (!item) return
    
    try {
      wx.showLoading({ title: '更新中...' })
      
      const data = {
        dishFlavor: item.dishFlavor || ''
      }
      
      if (item.dishId) {
        data.dishId = item.dishId
      } else {
        data.setmealId = item.setmealId
      }
      
      const res = await cartApi.add(data)
      
      if (res.code === 1) {
        // 重新加载购物车数据
        this.loadCartData()
      } else {
        throw new Error(res.msg || '更新失败')
      }
    } catch (error) {
      console.error('增加数量失败:', error)
      wx.showToast({
        title: error.message || '更新失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 减少商品数量
  async decreaseQuantity(e) {
    const itemId = e.currentTarget.dataset.id
    const item = this.data.cartItems.find(item => item.id === itemId)
    
    if (!item || item.number <= 1) return
    
    try {
      wx.showLoading({ title: '更新中...' })
      
      const data = {
        dishFlavor: item.dishFlavor || ''
      }
      
      if (item.dishId) {
        data.dishId = item.dishId
      } else {
        data.setmealId = item.setmealId
      }
      
      const res = await cartApi.sub(data)
      
      if (res.code === 1) {
        // 重新加载购物车数据
        this.loadCartData()
      } else {
        throw new Error(res.msg || '更新失败')
      }
    } catch (error) {
      console.error('减少数量失败:', error)
      wx.showToast({
        title: error.message || '更新失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 删除商品
  async deleteItem(e) {
    const itemId = e.currentTarget.dataset.id
    const item = this.data.cartItems.find(item => item.id === itemId)
    
    if (!item) return
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除"${item.name}"吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '删除中...' })
            
            const data = {
              dishFlavor: item.dishFlavor || ''
            }
            
            if (item.dishId) {
              data.dishId = item.dishId
            } else {
              data.setmealId = item.setmealId
            }
            
            const deleteRes = await cartApi.sub(data)
            
            if (deleteRes.code === 1) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
              // 重新加载购物车数据
              this.loadCartData()
            } else {
              throw new Error(deleteRes.msg || '删除失败')
            }
          } catch (error) {
            console.error('删除商品失败:', error)
            wx.showToast({
              title: error.message || '删除失败',
              icon: 'none'
            })
          } finally {
            wx.hideLoading()
          }
        }
      }
    })
  },

  // 清空购物车
  async clearCart() {
    if (this.data.cartItems.length === 0) return
    
    wx.showModal({
      title: '确认清空',
      content: '确定要清空购物车吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '清空中...' })
            
            const clearRes = await cartApi.clear()
            
            if (clearRes.code === 1) {
              wx.showToast({
                title: '清空成功',
                icon: 'success'
              })
              // 重新加载购物车数据
              this.loadCartData()
            } else {
              throw new Error(clearRes.msg || '清空失败')
            }
          } catch (error) {
            console.error('清空购物车失败:', error)
            wx.showToast({
              title: error.message || '清空失败',
              icon: 'none'
            })
          } finally {
            wx.hideLoading()
          }
        }
      }
    })
  },

  // 去结算
  goToCheckout() {
    if (this.data.selectedItems.length === 0) {
      wx.showToast({
        title: '请选择要结算的商品',
        icon: 'none'
      })
      return
    }
    
    // 跳转到订单确认页面
    wx.navigateTo({
      url: '/pages/order/order'
    })
  },

  // 继续购物
  continueShopping() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },

  // 跳转到商品详情
  goToDetail(e) {
    const { id, type } = e.currentTarget.dataset
    
    if (type === 'dish') {
      wx.navigateTo({
        url: `/pages/dish/dish?id=${id}`
      })
    } else {
      wx.navigateTo({
        url: `/pages/setmeal/setmeal?id=${id}`
      })
    }
  }
})
